package async

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"go.uber.org/zap"
	"runtime"
	"sensi/common/frame"
)

func Exec(ctx *gin.Context, cb func(ctx *gin.Context) error)  {
	ctx = ctx.Copy()
	go func() {
		var err error
		defer func() {
			msg := recover()
			if msg != nil {
				switch e := msg.(type) {
				case runtime.Error:
					err = errors.Wrapf(e, "panic runtime error: %v", e)
				default:
					err = errors.New(fmt.Sprintf("panic error: %v", e))
				}
			}
			if err != nil {
				frame.Logger(ctx).Error("execute goroutine failure", zap.Error(err))
			}
		}()
		err = cb(ctx)
	}()
}
